<?php
    /**
     * Created by PhpStorm.
     * User: long
     * Date: 2018/9/28
     * Time: 下午5:59
     */

    namespace app\member\home;

    use app\common\utils\UtilEncryption;
    use app\common\utils\UtilJwt;
    use app\member\logic\Member;
    use app\member\model\MemberInfoModel;
    use app\member\model\MemberModel;
    use think\Cache;
    use think\Controller;

    class Login extends Controller
    {

        protected function check_validate($data,$type)
        {

            $result = $this->validate($data,$type);
            (true !== $result) ? $this->error($result) : null;
        }

        protected function check_validate_param($type)
        {

            $data   = $this->request->param();
            $result = $this->validate($data,$type);
            (true !== $result) ? $this->error($result) : $data;
        }

        /**
         * 用户注册页面
         *
         * api GET /member/Login/register
         *
         * @return mixed
         */
        public function register()
        {


            $data                     = $this->request->param();

            $datas['referrer_phones'] = $data['referrer_phone'];
            if (isset($data['referrer_phone']))
            {
                $key = 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDAQEP73sZ8VLb1zcJJOPnkJrIziI8WoxxslARPplWxA5/VZltGoJPile3Qe56nKRQx2VeOv3zdVc3ta8iPAC5XTLA0R6L/7N6oHKU6EYapJOJeJ1T+TXqOT9N6UncJ+vUd7Ju/SYtvCCas07FbnpS6bq5wwIDAQA';

                $referrer_phone = UtilJwt::decode($data['referrer_phone'],$key);

                if (!isset($data['type'])){
                    $data['type']             = '';
                }
                $datas['referrer_phone'] = $referrer_phone;
                $datas['type']           = $data['type'];


                return $this->assign($datas)->fetch();

            }
            else
            {
                $datas['referrer_phone'] = '';
                $datas['type']           = '';
                return $this->assign($datas)->fetch();
            }


        }

        /**
         * 用户注册
         * api GET /member/Login/save
         *
         * @param int $phone          手机号码
         * @param int $password       登陆密码
         * @param int $re_password    确认登陆密码
         * @param int $validate_code  验证码
         * @param int $referrer_phone 推荐人手机号没有则不提交这个字段
         *
         * @return array code 200成功500错误
         * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
         */
        public function save()
        {

            $data['type'] = '';
            $data         = $this->request->param(); //获取参数
            // 验证
            $this->check_validate($data,'Auth.register');
            //注册用户

            $referrer_phone = isset($data['referrer_phone']) ? $data['referrer_phone'] : false; //介绍人


            //            //当验证码正确时
            if (Cache::get('timephone_' . $data['phone']) == $data['validate_code'])
            {

                $reqst = Member::app_register($data['phone'],$data['password'],$referrer_phone,$data);
                if (isset($reqst['success']))
                {
                    $this->success($reqst['success']);
                }
                else
                {
                    $this->error($reqst['error']);
                }

            }
            else
            {

                $this->error('验证码不正确，或已过期，请重新输入！');

            }
        }

        public function Make_info()
        {

            $data['type'] = '';
            $data         = $this->request->param(); //获取参数
            if (empty($data['referrer_phone']))
            {
                $data['referrer_phone'] = '';
            }
            if (empty($data['type']))
            {
                $data['type'] = '';
            }
            return $this->assign('data',$data)->fetch('qr');
        }

        /**
         * 推广二维码检查
         */
        public function Make_QR_code()
        {

            $data = $this->request->param(); //获取参数

            //            if (!captcha_check($data['csrf']))
            //            {
            //                $this->error($data);
            //            }
            /************************/

            $user = MemberModel::where(['phone' => $data['phone']])->find();
            if (empty($user))
            {
                $this->error('您还没有注册哦！');
            }

            $key = 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDAQEP73sZ8VLb1zcJJOPnkJrIziI8WoxxslARPplWxA5/VZltGoJPile3Qe56nKRQx2VeOv3zdVc3ta8iPAC5XTLA0R6L/7N6oHKU6EYapJOJeJ1T+TXqOT9N6UncJ+vUd7Ju/SYtvCCas07FbnpS6bq5wwIDAQA';

            $phone = UtilJwt::encode($data['phone'],$key);
            if (empty($data['referrer_phone']))
            {
                $datas['referrer_phone'] = '';
            }
            $datas['phone']          = $phone;
            $datas['referrer_phone'] = $data['referrer_phone'];
            $this->success('成功','',$datas);
        }

        /**
         * 获取手机验证码（注册）
         * api GET /member/auth/push_phone_code
         *
         * @param int phone 手机号码
         *
         * @return array data 返回值
         * @throws \think\db\exception\DataNotFoundException
         * @throws \think\db\exception\ModelNotFoundException
         * @throws \think\exception        \DbException
         */
        public function push_phone_code()
        {

            $data = $this->request->param(); //获取参数
            // 验证

            $res = Member::sendPhoneCode($data);
            if ($res['type'] == 'success')
            {
                $this->success($res['msg']);
            }
            else
            {
                $this->error($res['msg']);

            }
        }

        /**
         * app下载
         *
         * @return mixed
         */
        public function download()
        {

            $this->redirect('versions/download/index');

            $data = $this->request->param(); //获取参数
            if (empty($data['referrer_phone']))
            {
                $data['referrer_phone'] = '';
            }

            $this->assign('ios',url('versions/download/ios'));
            $this->assign('android',url('versions/download/android'));

            return $this->fetch('download');
        }

        /**
         * 登陆页面
         *
         * api GET /member/UserLogin/login
         *
         * @return mixed
         */
        public function login()
        {

            $data['type'] = '';
            $data         = $this->request->param();
            if (empty($data['referrer_phone']))
            {
                $data['referrer_phone'] = '';
            }
            if (empty($data['type']))
            {
                $data['type'] = '';
            }
            return $this->assign('data',$data)->fetch('userlogin/qr');

        }

        /**
         * 网页登陆
         */
        public function weblogin()
        {

            $data = $this->request->param();
            // 验证
            $this->check_validate($data,'Auth.login');
            if (empty($data['referrer_phone']))
            {
                $data['referrer_phone'] = '';
            }

            $phone = $data['phone'];
            $pwd   = $data['password'];

            $pwd   = UtilEncryption::encryptMd5($pwd,config('member_pwd_key'));


            $member_info = MemberModel::field('id,phone,password,status')->where([
                'phone'    => $phone,
                'password' => $pwd
            ])->find();

            if ($member_info)
            {
                if ($member_info['status'] == 0)
                {
                    $this->error('账号已冻结，请联系客服！');
                }

                $member = MemberInfoModel::getMemberInfo($member_info['id']);

                $member['token']          = UtilJwt::encode([
                    'member_id'   => $member_info->id,
                    'phone'       => $member_info->phone,
                    'create_time' => time()
                ],config('JwtKey'));
                $member['referrer_phone'] = $data['referrer_phone'];
                $this->success('登陆成功！','',$member);
            }
            else
            {
                $this->error('用户不存在或密码错误！');
            }
        }
    }